//
//  PywNoticeView.m
//  PywSdk
//
//  Created by zhj on 2018/8/14.
//

#import "PywNoticeView.h"
#import <WebKit/WebKit.h>
#import "UIImage+Pyw.h"
#import "PywMasonry.h"
#import "PywAppInfo.h"
#import "LocalInfoUtil.h"


@interface PywNoticeView()<WKNavigationDelegate>
@property (nonatomic,strong) WKWebView* wkWeb;
@property (nonatomic,strong) UILabel* titleLable;
@property (nonatomic,strong) UIButton* closeBtn;
@property (nonatomic,strong) UIView* divider;
@property (nonatomic,strong) UIButton* notShowBtn;
@property (nonatomic) int32_t msgId;
@end


@implementation PywNoticeView

static NSString* const KEY = @"pyw_anoun_status";

-(instancetype) init{
    self = [super init];
    if(self){
        [self setUp];
    }
    return self;
}

-(void) setUp{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 20.f;
    self.layer.masksToBounds = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?NO:YES;
    self.alpha = 1;
    
    [self addSubview:self.titleLable];
    [self addSubview:self.closeBtn];
    [self addSubview:self.divider];
    [self addSubview:self.wkWeb];
    [self addSubview:self.notShowBtn];
    [self layoutSub];
}

-(void) layoutSub{
    __weak typeof(self) weakSelf = self;
    [self.titleLable mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.mas_left);
        make.top.mas_equalTo(weakSelf.mas_top);
        make.right.mas_equalTo(weakSelf.mas_right);
        make.height.mas_equalTo(40);
    }];
    [self.closeBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.titleLable.mas_top);
        make.bottom.mas_equalTo(weakSelf.titleLable.mas_bottom);
        make.right.mas_equalTo(weakSelf.titleLable.mas_right).offset(-10);
    }];
    [self.divider mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.titleLable.mas_bottom);
        make.left.mas_equalTo(weakSelf.mas_left);
        make.right.mas_equalTo(weakSelf.mas_right);
        make.height.mas_equalTo(1);
    }];
    [self.notShowBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.bottom.mas_equalTo(weakSelf.mas_bottom);
        make.height.mas_equalTo(20);
        make.left.mas_equalTo(weakSelf.mas_left).offset(10);
    }];
    [self.wkWeb mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.equalTo(weakSelf.divider.mas_bottom);
        make.left.mas_equalTo(weakSelf.mas_left);
        make.right.mas_equalTo(weakSelf.mas_right);
        make.bottom.equalTo(weakSelf.notShowBtn.mas_top);
    }];
}

-(void) add2SuperView:(UIView *) superView withUrl:(NSString *) url andMsgId:(int32_t) mid{
    _msgId = mid;
    [superView addSubview:self];
    [self mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.center.offset(0);
        NSInteger viewWidth = [UIScreen mainScreen].bounds.size.width >
        [UIScreen mainScreen].bounds.size.height ?
        [UIScreen mainScreen].bounds.size.height :
        [UIScreen mainScreen].bounds.size.width;
        viewWidth = MIN(viewWidth, 500);
        make.width.equalTo(@(viewWidth * 0.85));
        if (viewWidth%320 == 0 || viewWidth%480 == 0) {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.65:0.75;
            make.height.equalTo(@(viewWidth * height));
        }else {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.58:0.65;
            make.height.equalTo(@(viewWidth * height));
        }
    }];
    [self showUrlPage:url];
}

-(void) showUrlPage:(NSString *)urlString{
    NSURL * url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [self.wkWeb loadRequest:request];
}


- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
        
    }
}


-(WKWebView *) wkWeb{
    if(!_wkWeb){
        // 设置偏好设置
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        //是否支持JavaScript
        config.preferences.javaScriptEnabled = YES;
        //不通过用户交互，是否可以打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        _wkWeb = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:config];
        _wkWeb.navigationDelegate = self;
    }
    return _wkWeb;
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:
(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *scheme = navigationAction.request.URL.scheme.lowercaseString;
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    NSString *parm = navigationAction.request.URL.parameterString;
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && [scheme containsString:@"pywapp"]
        && [hostname containsString:@"nativeapi"]) {
        self.titleLable.text = parm;
        // 不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


-(UILabel *) titleLable{
    if(!_titleLable){
        _titleLable = [UILabel new];
        [_titleLable setTextColor:[UIColor blackColor]];
        [_titleLable setBackgroundColor:UIColorFromRGB(0xfafafa)];
        [_titleLable setText:@"公告"];
        [_titleLable setTextAlignment:NSTextAlignmentCenter];
    }
    return _titleLable;
}

-(UIButton *) closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton new];
        [_closeBtn setImage:[UIImage imageWithName:@"icon_close_normal"] forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeTap) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

- (UIButton *)notShowBtn
{
    if (!_notShowBtn) {
        _notShowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _notShowBtn.backgroundColor = [UIColor clearColor];
        _notShowBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//        _notShowBtn.tag = ButtonTag_IsReadDisclaimer;
        
//        [_notShowBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
//        [_notShowBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
        
        [_notShowBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [_notShowBtn setTitle:@"不再提示" forState:UIControlStateNormal];
        [_notShowBtn setImage:[UIImage imageWithName:@"icon_isread_selected"] forState:UIControlStateNormal];
        [_notShowBtn setImage:[UIImage imageWithName:@"icon_isread_normal"] forState:UIControlStateSelected];
        [_notShowBtn addTarget:self action:@selector(notShowClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _notShowBtn;
}

-(UIView *) divider{
    if(!_divider){
        _divider = [UIView new];
        [_divider setBackgroundColor:UIColorFromRGB(0xd2d2d2)];
    }
    return _divider;
}

-(void) notShowClick:(UIButton *) sender{
    self.notShowBtn.selected = !sender.selected;
    [self saveMsgStatus:self.notShowBtn.selected];
}

/**
 * yes-notshow
 **/
-(void) saveMsgStatus:(BOOL) sta{
    [LocalInfoUtil saveMsgStatus:sta withMsgId:_msgId];
}

-(void) closeTap{
    NSLog(@"关闭界面");
    if(_onViewClose){
        _onViewClose(self);
    }
}

@end
